<template>
	<view class="postLaout">
		<post-nav-bar title="帖子详情"></post-nav-bar>
		<view class="blank"></view>
		<view class="postmaster">
			<view class="left">
				<view class="avatar">
					<image
					  v-if="dish.profilePicture"
					  :src="dish.profilePicture + '?t=' + Date.now()"
					  class="avatar"
					  mode="aspectFill"
					/>
					<!-- 当没有提供 profilePicture 时，显示默认图片 -->
					<image
					  v-else
					  src="../../static/image/user/user.jpg"
					  class="avatar"									 
					  mode="aspectFill"
					/>
				</view>
				<view class="name">{{dish.username}}</view>
			</view>
			<view class="right">
				<button class="flow-btn" @click="follow" v-if ="!dish.follow" plain>+关注</button>
				<button class="disflow-btn" @click="disfollow"  v-else plain>已关注</button>
			</view>
		</view>
		<view class="content">
			<view class="title">{{dish.name}}</view>
			<view class="keywords">
				<view v-for="(tag, index) in tags" :key="index" class="tag">
				    {{ tag }}
				</view>
			</view>
			<view class="main-img-box">
				<image :src="getImage(dish.imageUrl)" mode="aspectFill" class="main-img"></image>
			</view>
			<view class="divier">
				----------------材料------------------
			</view>
			<view class="material-box">
				<view class="material" v-for="(item, index) in dish.material" :key="index">
					{{ item }}
				</view>
			</view>
			<view class="divier">
				----------------正文------------------
			</view>
			<view class="body">
				<view class="body-item" v-for="(item, index) in bodys" :key="index">
					<view class="step">
						<uni-icons type="flag" color="#ff4d4f" size="28"></uni-icons>
						<view class="step-number">
							步骤{{index + 1}}
						</view>
						<view class="step-text">{{item.step}}</view>
						
					</view>
					<view class="step-img-box" v-if="item.image !== '' && item.imgage!== null">
						<image :src="getImage(item.Image)" mode="aspectFill" class="step-img"></image>
					</view>
				</view>
			</view>
			<view class="other-box">
				<uni-icons type="compose" color="#ccc" size="28"></uni-icons>
				{{dish.updatedAt}}
			</view>
		</view>
		
		
		<view class="operration-box">
			<view class="box">
				<uni-icons type="hand-up" size="30" :color="op_controller.good" @click="like_up"></uni-icons>
				<text :style="'color:' + op_controller.good">{{format(dish.likes)}}</text>
			</view>
			<view class="box">
				<uni-icons type="hand-down" size="30" :color="op_controller.bad" @click="like_down"></uni-icons>
				<text :style="'color:' + op_controller.bad">{{op_controller.bad_text}}</text>
			</view>
			<view class="box">
				<uni-icons type="star" size="30" :color="op_controller.collect" @click="star"></uni-icons>
				<text  :style="'color:' + op_controller.collect">{{op_controller.collect_text}}</text>
			</view>
		</view>
		
		
		<view class="comment-section">
			<view class="title">
				评论区
			</view>
			<view class="comment-blank" v-if="commentList.length == 0">
				<uni-icons type="chatboxes" size="50" color="#888"></uni-icons>
				<text>这篇美食还没有评论哦，发评支持一下</text>
			</view>
			<view class="comment" v-for="(item,index) in commentList" :key=index>
				<view class="left">
					<view class="avatar">
						<image :src="getAvatar(item.id)" mode="aspectFill"></image>
					</view>
				</view>
				<view class="right">
					<view class="commenter">
						<view class="name">{{item.name}}</view>
					</view>
					<view class="comment-content">
						{{item.content}}
					</view>
					<view class="status">
						<view class="left">
							<view class="time">{{item.time}}</view>
							<button class="reply-btn" @click="reply_comment(item.comment_id)" plain>回复</button>
							<button class="reply-btn" @click="delete_comment(item.comment_id, item.id)" plain >删除</button>
						</view>
						<view class="right">
							
							<view class="like">
								<uni-icons type="hand-up" color="#ccc" size="20"></uni-icons>
								{{item.likes}}
							</view>
						</view>
					</view>
					<view class="reply-section">
						<view class="reply-content" v-for="(comment,index) in item.comments" :key=index>
							<text class="replyer-name">{{comment.name}}:</text>
							<text class="reply-text">
								{{comment.content}}
							</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<view class="fill"></view>
		
		<view class="comment-input-box">
			<view class="input-area" @click="comment_input">
				发送我的第一条评论吧！
			</view>
		</view>
		
		<view class="comment-modal" v-if="comment_input_show" @click="() => {comment_input_show = false}">
			<view class="comment-write" :style="'bottom:' + keyboardHeight +'px'" @click.stop>
				<textarea :adjust-position="false" class="comment-textarea" v-model="new_comment.content" cols="200" rows="8" placeholder="点击输入评论"></textarea>
				<view class="button-box">
					<button class="comment-btn" @click="new_comment.content = ''">清空</button>
					<button class="comment-btn" @click="add_comment" >发布</button>
				</view>
			</view>
		</view>
		

	</view>
</template>

<script setup>
import { onMounted, onUnmounted, reactive, ref } from 'vue';
import { appUrl } from '../../main';
import LoginViewVue from '../LoginView/LoginView.vue';

//数据
const token = ref("")
const dish = ref({})
const tags = ref([])
const bodys = ref([])
const commentList = ref([])
//函数
const initTag = () => {
	const tagArray = dish.value.category.split(',').filter(tag => tag.trim() !== ''); // 分割字符串并过滤空项
	tags.value = tagArray;
}
const getImage = (path) => {
	return "https://xiaoxiaobaiyang.oss-cn-shenzhen.aliyuncs.com/food_moment_discover/train/data/" + path
}
const getAvatar = (userId) => {
	return "https://xiaoxiaobaiyang.oss-cn-shenzhen.aliyuncs.com/food_moment_discover/image/avatar/" + userId + ".jpg"
}
const initBody = () => {
	let body = dish.value.body
	let imageUrls = dish.value.recipes
	let imageUrlMap = imageUrls.reduce((acc, item) => {
	        const stepNumber = parseInt(item.imageUrl.split('/')[1].split('.')[0], 10);
	        acc[stepNumber] = item.imageUrl;
	        return acc;
	    }, {});
	let result = body.map(stepText => {
	        const stepNumber = parseInt(stepText.split(' ')[0], 10);
	        return {
	            step: stepText.split(' ')[3],
	            Image: imageUrlMap[stepNumber] || ''
	        };
	    });
	
	bodys.value = result	
}
//评论查询
const initComment = () => {
	commentList.value = dish.value.comments
}


//评论发送
//键盘高度
const keyboardHeight = ref(0)
//评论数据
const new_comment = ref({
	foreignId: 0,
	reply: 0,
	content: ""
})
//评论界面高度
const inputHeight = ref(0)
//显示评论模态框
const comment_input_show = ref(false)

//控制键盘高度
const change_keyboardHeight = (res) => {
	 keyboardHeight.value = res.height
}
//编写主评论
const comment_input = () => {
	comment_input_show.value = true
	new_comment.value.foreignId = dish.value.dishId
	new_comment.value.reply = 0
}
//发送评论
const add_comment = () => {
	if(new_comment.value.content == ''){
		uni.showToast({
			icon:'error',
			title:"不能写空评论哦",
			duration: 1000
		})
		return
	}
	
	uni.request({
	    url: appUrl+'/comment/add',
	    data: new_comment.value,
		header:{
			'token': token.value
		},
		method: "post"
	}).then((res) => {
		if(res.data.status == 200){
			if(new_comment.value.reply == 0){
				commentList.value.push(res.data.data)
			}else{
				for (let i = 0; i < commentList.value.length; i++) {
				    if (commentList.value[i].comment_id === new_comment.value.foreignId) {
				        // 找到匹配的comment_id后，检查是否存在comments数组
				        if (commentList.value[i].comments === undefined) {
				            // 如果不存在，则初始化一个空数组
				            commentList.value[i].comments = [];
				        }
				        // 向comments数组中添加新的评论
				        commentList.value[i].comments.push(res.data.data);
				        break 
				    }
				}
			}
			
			uni.showToast({
				title: '评论成功',
				duration: 1000,
			});
		}else{
			console.log(res.data);
			uni.showToast({
				title: '发送失败',
				icon: "error",
				duration: 1000,
			});
		}
	})
	
	comment_input_show.value = false
}
//回复评论
const reply_comment = (id) => {
	comment_input_show.value = true
	new_comment.value.foreignId = id
	new_comment.value.reply = 1
}
const delete_comment = (comment_id, userId) => {
	if(userId !== uni.getStorageSync("userId")){
		uni.showToast({
			icon:'error',
			title: "只能删除自己的评论"
		})
		return
	}
	uni.showModal({
		title: '提示',
		content: '要删除评论吗',
		confirmColor: "#FF4D4F",
		success: function(res) {
			if (res.confirm) {
				for (let i = 0; i < commentList.value.length; i++) {
					if(commentList.value[i].comment_id === comment_id){
						uni.request({
						    url: appUrl+'/comment/delete',
						    data: {
								commentId: comment_id,
								reply: 0
							},
							method: "post"
						}).then((res) => {
							if(res.data.status == 200){
								commentList.value.splice(i, 1)
								uni.showToast({
									title: '删除成功',
									duration: 1000,
								});
							}else{
								uni.showToast({
									title: '发送失败',
									icon: "error",
									duration: 1000,
								});
							}
						})
						return
					}
					if (commentList.value[i].comments === undefined) {
						for (let j = 0; j < commentList.value[i].comments.length; j++){
							if( commentList.value[i].comments[j].comment_id === comment_id ){
								uni.request({
								    url: appUrl+'/comment/delete',
								    data: {
										commentId: comment_id,
										reply: 1
									},
									method: "post"
								}).then((res) => {
									if(res.data.status == 200){
										commentList.value[i].comments.splice(j, 1)
										uni.showToast({
											title: '删除成功',
											duration: 1000,
										});
									}else{
										uni.showToast({
											title: '发送失败',
											icon: "error",
											duration: 1000,
										});
									}
								})
								return
							}
						}
					}
				    
				}
			}
		}
	})
}

//帖子的数据
//关注
const raw_follow = ref(false)
const raw_collect = ref(false)
const follow = () => {
	uni.showToast({
		title:"关注成功"
	})
	dish.value.follow = true
}
const disfollow = () => {
	uni.showToast({
		title:"取关成功"
	})
	dish.value.follow = false
	
}
//赞踩收藏
//控制
const op_controller = ref({
	like: false,
	dis_like: false,
	good: "#aaa",
	bad:"#aaa",
	bad_text:"点踩",
	collect:"#aaa",
	collect_text: "收藏"
})
//显示控制
const format = (num) => {
		if (num >= 100000) {
			return Math.round(num / 10000) + "w"
		} else if (num >= 10000) {
			return (Math.round(num / 1000)) / 10 + "w"
		} else {
			return num
		}
	}
//初始化
const initOp = () => {
	raw_follow.value = dish.value.follow
	raw_collect.value = dish.value.collect
	if(dish.value.collect){
		op_controller.value.collect = "#FF4D4F"
		op_controller.value.collect_text = "已收藏"
	}else{
		op_controller.value.collect = "#aaa"
		op_controller.value.collect_text = "收藏"
	}
}
const like_up = () => {
	if(op_controller.value.like){
		op_controller.value.like = false
		dish.value.likes--
		op_controller.value.good = "#aaa"
		
	}else{
		op_controller.value.like = true
		dish.value.likes++
		op_controller.value.good = "#FF4D4F"
		if(op_controller.value.dis_like){
			op_controller.value.dis_like = false
			op_controller.value.bad_text = "点踩"
			op_controller.value.bad = "#aaa"
		}
	}
}
const like_down = () => {
	if(op_controller.value.dis_like){
		op_controller.value.dis_like = false
		op_controller.value.bad_text = "点踩"
		op_controller.value.bad = "#aaa"
		
	}else{
		op_controller.value.dis_like = true
		op_controller.value.bad_text = "已点踩"
		op_controller.value.bad = "#FF4D4F"
		if(op_controller.value.like){
			op_controller.value.like = false
			dish.value.likes--
			op_controller.value.good = "#aaa"
		}
	}
}
const star = () => {
	if(dish.value.collect){
		dish.value.collect = false
		op_controller.value.collect = "#aaa"
		op_controller.value.collect_text = "收藏"
	}else{
		dish.value.collect = true
		op_controller.value.collect = "#FF4D4F"
		op_controller.value.collect_text = "已收藏"
	}
}




//钩子
onMounted(() => {
	
	let id = uni.getStorageSync("dishId")
	
	token.value = uni.getStorageSync("token")
	if(token.value === null || token.value === ""){
		uni.showToast({
			icon:'error',
			title:"用户未登录",
			duration: 1000
		})
		uni.reLaunch({
			url:"/pages/UserView/UserView"
		})
	}
	
	try{
		uni.request({
			url: appUrl+'/dish/dishBody',
			header:{
				'token': token.value
			},
			data: {
				dishId:id
			},
			method: "post"
		}).then(res => {
			dish.value = res.data.data
			initTag()
			initBody()
			initComment()
			initOp()
			
		})
	}catch(error){
		uni.showToast({
			title:"信息获取失败",
			icon:"error"
		})
	}
	
	uni.getSystemInfo({
	  success: function(res) {
	    if (res.platform === 'android') {
	     uni.onKeyboardHeightChange(change_keyboardHeight)  
	    } 
	  },
	  fail: function(err) {
	    console.error("获取系统信息失败", err);
	  }
	});
})

onUnmounted(() => {
	let master_follow = 0
	let post_favorite = 0
	let like = 0
	if(dish.value.follow != raw_follow.value){
		if(dish.value.follow){
			master_follow = 1
		}else{
			master_follow = -1
		}
	}
	if(dish.value.collect != raw_collect.value){
		if(dish.value.collect){
			post_favorite = 1
		}else{
			post_favorite = -1
		}
		
	}
	if(op_controller.value.like){
		like = 1
	}
	if(op_controller.value.dis_like){
		like = -1
	}
	
	uni.request({
		url: appUrl+'/dish/back',
		header:{
			'token': token.value
		},
		data: {
			id:dish.value.dishId,
			like:like,
			follow: master_follow,
			favorite: post_favorite
			
		},
		method: "post"
	}).then(res => {
		console.log("数据更新成功");
	})
	
	uni.getSystemInfo({
	  success: function(res) {
	    if (res.platform === 'android') {
	     uni.offKeyboardHeightChange(change_keyboardHeight)
	    } 
	  },
	  fail: function(err) {
	    console.error("获取系统信息失败", err);
	  }
	});
})

</script>

<style lang="scss" scoped>
.blank {
	height: 60rpx;
	background-color: ghostwhite;
	position: fixed;
	top: 50rpx;
	left: 0;
	width: 100%;
	z-index: 8;
}
	
.postLaout{
	.postmaster{
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 30rpx;
		height: 100rpx;
		.left{
			display: flex;
			justify-content: center;
			align-items: center;
			.avatar{
				width: 70rpx;
				height: 70rpx;
				border-radius: 50%;
				overflow: hidden;
				image {
					width: 100%;
					height: 100%;
				}
			}
			.name{
				margin-left: 20rpx;
			}
		}
		.right{
			.flow-btn{
				height: 50rpx;
				display: flex;
				align-items: center;
				font-size: 15px;
				color: #fff;
				background-color: #FF4D4F;
				border: 1px #FF4D4F solid;
			}
			.disflow-btn{

				
				height: 50rpx;
				display: flex;
				align-items: center;
				font-size: 15px;
				color: #FF4D4F;
				border: 1px #FF4D4F solid;
			}
		}
	}
	.content{
		padding: 0 30rpx;
		margin-bottom: 30rpx;
		.title{
			font-size: 25px;
		}
		.divier{
			display: flex;
			justify-content: center;
			align-items: center;
		}
		.keywords{
			display: flex;
			flex-wrap: wrap;
			.tag {
				height: 20px;
				display: flex;
				align-items: center;
				justify-content: center;
				margin: 10px 10px 0 0;
				padding: 0 5px;
				border-radius: 4px;
				font-size: 10px;
				color: rgb(221, 213, 158);
				background-color: rgba(221, 213, 158, 0.1);
				border: 1px solid rgb(221, 213, 158);
			}
		}
		.main-img-box{
			margin: 30rpx 0;
			width: 100%;
			border-radius: 10px;
			overflow: hidden;
			.main-img{
				width: 100%;
			}
		}
		.material-box{
			margin-left: 50rpx;
		}
		.body{
			.body-item{
				margin-top: 100rpx;
				.step{
					padding: 20rpx;
					background-color: rgba(255, 190, 187, 0.2);
					border-radius: 10px;
					display: flex;
					align-items: center;
					justify-content: left;
					.step-number{
						margin:0 10rpx;
						width: 100rpx;
						color: #FF4D4F;
						font-weight: bold;
					}
					.step-text{
						margin-left: 10rpx;
					}
				}
				.step-img-box{
					margin: 30rpx 0;
					width: 100%;
					border-radius: 20px;
					overflow: hidden;
					.step-img{
						width: 100%;
					}
				}
				
				&:first-child{
					margin-top: 50rpx;
				}
			}
			
		}
	}
	.operration-box{
		border-bottom:6px solid #eee ;
		margin: 20rpx 0 0 0;
		width: 100%;
		height: 130rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		.box{
			width: 33%;
			height: 100rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			flex-direction: column;
		}

	}
	
	
	.comment-section{
		padding: 0 30rpx;
		margin: 20rpx 0;
		.title{
			font-size: 20px;
		}
		.comment-blank{
			height: 20vh;
			width: 100%;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			color: #888;
		}
		.comment{
			display: flex;
			justify-content: center;
			margin-top: 30rpx;
			border-bottom:1px solid #eee;
			.left{
				height: 100%;
				width: 80rpx;
				.avatar{
					width: 70rpx;
					height: 70rpx;
					border-radius: 50%;
					overflow: hidden;
					image {
						width: 100%;
						height: 100%;
					}
				}
			}
			.right{
				margin-left: 20rpx;
				width: 590rpx;
				
				.commenter{
					width: 100%;
					font-size: 15px;
					color: #888;
				}
				.comment-content{
					font-size: 17px;
					padding: 15rpx 0;
				}
				.status{
					display: flex;
					justify-content: space-between;
					align-items: center;
					.left{
						width: 500rpx;
						overflow: hidden;
						display: flex;
						justify-content: space-between;
						align-items: center;
						.time{
							color: #888;
							margin-right: 5rpx;
						}
						.reply-btn{
							display: flex;
							justify-content: center;
							align-items: center;
							border: none;
							color: #aaa;
							height: 20px;
							width: 50px;
							padding: 0;
							font-size: 15px;
						}
					}
					.right{
						width: 100rpx;
						.like{
							display: flex;
							align-items: center;
							color: #CCC;
						}
					}
				}
				.reply-section{
					width: 100%;
					margin:30rpx 0;
					background-color: #F6F3F1;
					padding: 10rpx 30rpx;
					border-radius: 10px;
					.reply-content{
						font-size: 15px;
						margin: 5px 0;
						.replyer-name{
							color:#E06C75;
						}
						
					}
				}
			}
		}
	}
	.comment-input-box{
		margin: 0;
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		height: 80rpx;
		background-color: #fff;
		border-top: 1px solid #CCC;
		display: flex;
		justify-content: center;
		align-items: center;
		.input-area{
			width: 90%;
			height: 50rpx;
			background-color: #eee;
			border-radius: 50px;
			padding: 0 15px;
			display: flex;
			align-items: center;
			font-size: 15px;
			color: #888;
		}
	}
	.comment-modal {
		position: fixed;
		left: 0;
		bottom: 0;
		height: 100vh;
		width: 100vw;
		background-color: rgba(0, 0, 0, 0.5);
		.comment-write{
			position: absolute;
			width: 100vw;
			height: 18vh;
			background-color: #fff;
			border-radius: 10px 10px 0 0;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			.comment-textarea{
				margin-top: 2vh;
				box-sizing: border-box;
				background-color: #eee;
				width: 90%;
				height: 10vh;
				border-radius: 10px;
				padding: 13px;
			}
			.button-box{
				width: 90%;
				height: 5vh;
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-top: 1vh;
				.comment-btn{
					margin: 0;
					display: flex;
					justify-content: center;
					align-items: center;
					background-color: #FF4D4F;
					color: #fff;
					width: 25%;
					height: 4vh;
					font-size: 17px;
				}
			}
		}
	}
	.fill{
		width: 100%;
		height: 80rpx;
	}
}
</style>
